package com.ruoyi.web.controller.system;

import com.ruoyi.common.config.SsoConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.SsoLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SsoLoginController {
    @Autowired
    private SsoLoginService iSsoService;

    /**
     * 获取code相关信息
     *
     * @return 结果
     */
    @PostMapping("/user/ssoGetCodeUrl")
    public AjaxResult ssoGetCodeUrl() {
        AjaxResult ajax = AjaxResult.success();
        String authorizeRequestUrl = String.format(SsoConfig.getAuthorizeRequestUrl(), SsoConfig.getTenantId()) +
                "?response_type=" + SsoConfig.getResponseType() +
                "&response_mode=" + SsoConfig.getResponseMode() +
                "&state=" + SsoConfig.getState() +
                "&scope=" + SsoConfig.getScope() +
                "&client_id=" + SsoConfig.getClientId() +
                "&redirect_uri=" + SsoConfig.getRedirectUri() +
                "&sso_reload=" + SsoConfig.getSsoReload();
        ajax.put("authorizeRequestUrl", authorizeRequestUrl);
        return ajax;
    }

    @PostMapping("/user/ssoLogin")
    public AjaxResult login(@RequestBody Map<String, String> map) {
        AjaxResult ajax = AjaxResult.success();
        String code = map.get("code");
        ajax.put(Constants.TOKEN, iSsoService.login(code));
        return ajax;
    }

    @PostMapping("/user/checkToken")
    public AjaxResult checkToken(@RequestParam("state") String state, @RequestParam("token") String token) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", iSsoService.checkToken(state, token));
        return ajax;
    }

}
